package com.bj58.groupbuy.action.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.bj58.groupbuy.action.model.AllianceDataSourceReportVo;
import com.bj58.groupbuy.action.model.AllianceDataSummaryVoForMail;
import com.bj58.groupbuy.action.model.AllianceDataWirelessReportVo;
import com.bj58.groupbuy.action.model.EmailReportUser;
import com.bj58.groupbuy.action.model.ORKpiTarget;
import com.bj58.groupbuy.action.service.EmailReportService;
import com.bj58.groupbuy.action.service.EmailReportUserService;
import com.bj58.groupbuy.action.service.OnlineRevenueService;
import com.bj58.groupbuy.action.util.DateUtil;
import com.bj58.groupbuy.action.util.MailUtil;
import com.bj58.groupbuy.action.util.ReflectUtil;
import com.bj58.groupbuy.action.util.ResourcesUtil;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.PathUtil;
import com.bj58.wf.mvc.MvcController;

/**邮件报告 （代码已迁移至emailreport项目，仅留下在线收入汇总日报的发送）
 * @author HL
 *
 */
public class EmailReoprtController extends MvcController{
	private  EmailReportUserService emailReportUserService = ServiceLocator.get(EmailReportUserService.class);
	private  EmailReportService emailReportService = ServiceLocator.get(EmailReportService.class);
	private OnlineRevenueService onlineRevenueService = ServiceLocator.get(OnlineRevenueService.class);
	private SomePublicUtil  spu = new SomePublicUtil();
	private ReflectUtil reflectUtil = new ReflectUtil();
	private VelocityTools  vt = new VelocityTools();
	
		/**在线收入汇总日报
		 * 
		 */
		@SuppressWarnings("static-access")
		public String onlineRevenueIncomeDayReport(String searchDate){
			try {
				//velocity对象
				VelocityContext context = new VelocityContext();
				Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
				context.put("tools",tools);
				//读取模板内容
				String filepath =PathUtil.getWFNamespaceFolder()+"/emailtemp/ORIncomeDayReport.html";
				ResourcesUtil.setCharset(Charset.forName("utf-8"));
				FileInputStream inputStream = new FileInputStream(new File(filepath));
				String templateContext = ResourcesUtil.readString2(inputStream);
				inputStream.close();
				
				Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
				String nowDate = DateUtil.getStringDate(sDate,"yyyy-MM-dd");//查询日期（今）
				String yesterDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");//查询日期（昨）
				String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");//查询日期（一周）
				
				//收入汇总  - 分渠道收入及分渠道摊销数据
				List<AllianceDataSummaryVoForMail> rsNow = onlineRevenueService.ORIncomeData(" statDate='"+nowDate+"' "); //今日数据
				List<AllianceDataSummaryVoForMail> rsYester= onlineRevenueService.ORIncomeData(" statDate='"+yesterDate+"' ");//昨日数据
				List<AllianceDataSummaryVoForMail> rsLastWeek= onlineRevenueService.ORIncomeData(" statDate='"+lastWeek+"' ");//上周数据
				String monthFirstDay = DateUtil.getFirstDay(sDate);	//当月第一天
				List<AllianceDataSummaryVoForMail> rsMonth = onlineRevenueService.ORIncomeSumData(" statDate>='"+monthFirstDay+"' and statDate <='"+nowDate+"' "); //月累计数据
				if(null == rsNow || null == rsYester || null == rsLastWeek || null == rsMonth){  //数据缺失直接88
					return "";
				}
				
				//本月KPI目标
				String month = DateUtil.getStringDate(sDate,"yyyy-MM");//月份
				ORKpiTarget  kpi  =onlineRevenueService.getORKpiTarget(month);
				Map<String,Long> kpiMap = new HashMap<String,Long>();
				Field[] kpiFds = ORKpiTarget.class.getDeclaredFields();
				for(Field fd : kpiFds){
					String name = fd.getName();
					if(!"month".equals(name)){
						long value = Long.parseLong(reflectUtil.getGetterMethod(ORKpiTarget.class, ORKpiTarget.class.getDeclaredField(name)).invoke(kpi).toString());
						kpiMap.put(name, value);
					}
				}
				
				Map<String,AllianceDataSummaryVoForMail> dataMap = new HashMap<String, AllianceDataSummaryVoForMail>();
				dataMap.put(nowDate, rsNow.get(0));
				dataMap.put(yesterDate, rsYester.get(0));
				dataMap.put(lastWeek, rsLastWeek.get(0));
				dataMap.put("month", rsMonth.get(0));
				
				List<String>  dics = spu.getECDicByAnnotation(AllianceDataSummaryVoForMail.class);
				List<String>  rsList = new ArrayList<String>(); 
				Class<AllianceDataSummaryVoForMail> clazz = AllianceDataSummaryVoForMail.class;
				
				for(String dic : dics){
					String ename = dic.split(",")[0];
					String cname = dic.split(",")[1];
					
					if("allIncomeJX".equals(ename)){ //到驾校一点通的stop
						break;
					}
					
					if("statDate".equals(ename)){ //日期  先PASS
						continue;
					}
					StringBuffer value = new StringBuffer();
					value.append(cname+";"); //指标名
					
					//该指标的数据类型
					Field field = AllianceDataSummaryVoForMail.class.getDeclaredField(ename);
					Class<?> filedCls = field.getType();
					int  colType = 0; //数据类型  0 : 整型  1：浮点  2：百分比
					if(filedCls == int.class || filedCls == Integer.class || filedCls == long.class || filedCls == Long.class) {
						colType = 0 ; 
					}else if(filedCls == double.class || filedCls == Double.class) {
						if("adverPvRate".equals(ename) || "CTR".equals(ename)){ //此两类为百分比 其他为浮点
							colType = 2 ; 
						}else{
							colType = 1 ; 
						}
					} 
					//今日数据
					Object nowData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(nowDate));
					if(null != nowData){
						value.append(vt.tranValueByType(nowData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//昨日数据
					Object yesterData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(yesterDate));
					if(null != yesterData){
						value.append(vt.tranValueByType(yesterData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//环比
					if(null != nowData && null != yesterData){
						value.append(vt.compRate(nowData, yesterData)+";");
					}else{
						value.append("--"+";");
					}
					//上周数据
					Object lastWeekData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(lastWeek));
					if(null != lastWeekData){
						value.append(vt.tranValueByType(lastWeekData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//同比
					if(null != nowData && null != lastWeekData){
						value.append(vt.compRate(nowData, lastWeekData)+";");
					}else{
						value.append("--"+";");
					}
					//4类数据无需计算月累计和月均
					if("adverPvRate".equals(ename) || "CTR".equals(ename)  || "CPC".equals(ename)  || "ECPM".equals(ename)){
						value.append("--"+";"+"--"+";");
					}else{
						//月累计
						Object monthData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month"));
						if(null != monthData){
							value.append(vt.qfw((long)Double.parseDouble(monthData.toString()))+";");
						}else{
							value.append("--"+";");
						}
						//月均
						if(null != monthData){
							long  monthSum = (long)Double.parseDouble(monthData.toString());
							long subDay  = DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")); //总天数
							long avgData = monthSum/(subDay+1);
							value.append(vt.qfw(avgData)+";");
						}else{
							value.append("--"+";");
						}
					}
					
					//KPI月目标 && KPI剩余日均
					if(kpiMap.containsKey(ename) && kpiMap.get(ename) > 0){
						long monthKpi = kpiMap.get(ename);
						value.append(vt.qfw(monthKpi)+";");
						//月累计
						long monthData = (long)Double.parseDouble(reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month")).toString());
						int monthDaysNum = DateUtil.getDaysByMonth(nowDate); //当月总天数
						long subDay  = monthDaysNum - DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")) -1; //剩余天数
						
						long subKpiData = 0 ;
						if(subDay != 0 ){
							subKpiData = (monthKpi - monthData)/subDay;
						}else{
							subKpiData = (monthKpi - monthData);
						}
						value.append(vt.qfw(subKpiData)+";");
					}else{
						value.append("--"+";");
						value.append("--"+";");
					}
					rsList.add(value.toString());
				}

				context.put("nowDate",nowDate);
				context.put("yesterDate",yesterDate);
				context.put("lastWeek",lastWeek);
				context.put("rsList",rsList);
				
				//无线数据
				List<AllianceDataWirelessReportVo> wlList = emailReportService.adWLData(nowDate, yesterDate, lastWeek);
				if(null != wlList ){
					context.put("wlList",wlList);
				}

				/** 渠道数据 */
				List<String> dateList = new ArrayList<String>();
				dateList.add(nowDate);dateList.add(yesterDate);dateList.add(lastWeek);
				
				//渠道数据 - CPC渠道
				List<AllianceDataSourceReportVo> cpcQdList = emailReportService.adSourceData(dateList, 1);
				context.put("cpcQdList",cpcQdList);
				
				//CPC站外渠道收入
				List<AllianceDataSourceReportVo> cpcZwQdList = emailReportService.adSourceData(dateList, 2);
				context.put("cpcZwQdList",cpcZwQdList);
				
				//联盟重点合作方CPC收入
				List<AllianceDataSourceReportVo> cpcLMList = emailReportService.adSourceData(dateList, 3);
				context.put("cpcLMList",cpcLMList);
				
				VelocityEngine velocity  = new VelocityEngine();
				Velocity.setProperty("input.encoding", "utf-8");
				Velocity.setProperty("output.encoding", "utf-8");
				String content = templateContext;
				StringWriter out = new StringWriter();
				velocity.evaluate(context, out, "", content);
				content = out.toString();
				out.close();
				return content;
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		
		
		/**驾校一点通日报
		 * 
		 */
		@SuppressWarnings("static-access")
		public String jxydtDayReport(String searchDate){
			try {
				//velocity对象
				VelocityContext context = new VelocityContext();
				Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
				context.put("tools",tools);
				//读取模板内容
				String filepath =PathUtil.getWFNamespaceFolder()+"/emailtemp/JxydtDayReport.html";
				ResourcesUtil.setCharset(Charset.forName("utf-8"));
				FileInputStream inputStream = new FileInputStream(new File(filepath));
				String templateContext = ResourcesUtil.readString2(inputStream);
				inputStream.close();
				
				Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
				String nowDate = DateUtil.getStringDate(sDate,"yyyy-MM-dd");//查询日期（今）
				String yesterDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");//查询日期（昨）
				String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");//查询日期（一周）
				
				//收入汇总  - 分渠道收入及分渠道摊销数据
				List<AllianceDataSummaryVoForMail> rsNow = onlineRevenueService.ORIncomeData(" statDate='"+nowDate+"' "); //今日数据
				List<AllianceDataSummaryVoForMail> rsYester= onlineRevenueService.ORIncomeData(" statDate='"+yesterDate+"' ");//昨日数据
				List<AllianceDataSummaryVoForMail> rsLastWeek= onlineRevenueService.ORIncomeData(" statDate='"+lastWeek+"' ");//上周数据
				String monthFirstDay = DateUtil.getFirstDay(sDate);	//当月第一天
				List<AllianceDataSummaryVoForMail> rsMonth = onlineRevenueService.ORIncomeSumData(" statDate>='"+monthFirstDay+"' and statDate <='"+nowDate+"' "); //月累计数据
				if(null == rsNow || null == rsYester || null == rsLastWeek || null == rsMonth){  //数据缺失直接88
					return "";
				}
				
				//本月KPI目标
				String month = DateUtil.getStringDate(sDate,"yyyy-MM");//月份
				ORKpiTarget  kpi  =onlineRevenueService.getORKpiTarget(month);
				Map<String,Long> kpiMap = new HashMap<String,Long>();
				Field[] kpiFds = ORKpiTarget.class.getDeclaredFields();
				for(Field fd : kpiFds){
					String name = fd.getName();
					if(!"month".equals(name)){
						long value = Long.parseLong(reflectUtil.getGetterMethod(ORKpiTarget.class, ORKpiTarget.class.getDeclaredField(name)).invoke(kpi).toString());
						kpiMap.put(name, value);
					}
				}
				
				Map<String,AllianceDataSummaryVoForMail> dataMap = new HashMap<String, AllianceDataSummaryVoForMail>();
				dataMap.put(nowDate, rsNow.get(0));
				dataMap.put(yesterDate, rsYester.get(0));
				dataMap.put(lastWeek, rsLastWeek.get(0));
				dataMap.put("month", rsMonth.get(0));
				
				List<String>  dics = spu.getECDicByAnnotation(AllianceDataSummaryVoForMail.class);
				List<String>  rsList = new ArrayList<String>(); 
				Class<AllianceDataSummaryVoForMail> clazz = AllianceDataSummaryVoForMail.class;
				
				boolean deal = false;
				
				for(String dic : dics){
					String ename = dic.split(",")[0];
					String cname = dic.split(",")[1];
					
					
					if("allianceIncomeJX".equals(ename)){
						deal = true;
					}
					
					if(!deal || "amortizeIncomeJX".equals(ename)){ //联盟摊销收入也先PASS
						continue;
					}
					
					//stop
					if("brandZX".equals(ename)){
						break;
					}
					
					
					
					StringBuffer value = new StringBuffer();
					value.append(cname+";"); //指标名
					
					//该指标的数据类型
					Field field = AllianceDataSummaryVoForMail.class.getDeclaredField(ename);
					Class<?> filedCls = field.getType();
					int  colType = 0; //数据类型  0 : 整型  1：浮点  2：百分比
					if(filedCls == int.class || filedCls == Integer.class || filedCls == long.class || filedCls == Long.class) {
						colType = 0 ; 
					}else if(filedCls == double.class || filedCls == Double.class) {
						if("adverPvRate".equals(ename) || "CTR".equals(ename)){ //此两类为百分比 其他为浮点
							colType = 2 ; 
						}else{
							colType = 1 ; 
						}
					} 
					//今日数据
					Object nowData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(nowDate));
					if(null != nowData){
						value.append(vt.tranValueByType(nowData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//昨日数据
					Object yesterData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(yesterDate));
					if(null != yesterData){
						value.append(vt.tranValueByType(yesterData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//环比
					if(null != nowData && null != yesterData){
						value.append(vt.compRate(nowData, yesterData)+";");
					}else{
						value.append("--"+";");
					}
					//上周数据
					Object lastWeekData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(lastWeek));
					if(null != lastWeekData){
						value.append(vt.tranValueByType(lastWeekData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//同比
					if(null != nowData && null != lastWeekData){
						value.append(vt.compRate(nowData, lastWeekData)+";");
					}else{
						value.append("--"+";");
					}
					//4类数据无需计算月累计和月均
					if("adverPvRate".equals(ename) || "CTR".equals(ename)  || "CPC".equals(ename)  || "ECPM".equals(ename)){
						value.append("--"+";"+"--"+";");
					}else{
						//月累计
						Object monthData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month"));
						if(null != monthData){
							value.append(vt.qfw((long)Double.parseDouble(monthData.toString()))+";");
						}else{
							value.append("--"+";");
						}
						//月均
						if(null != monthData){
							long  monthSum = (long)Double.parseDouble(monthData.toString());
							long subDay  = DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")); //总天数
							long avgData = monthSum/(subDay+1);
							value.append(vt.qfw(avgData)+";");
						}else{
							value.append("--"+";");
						}
					}
					
					//KPI月目标 && KPI剩余日均
					if(kpiMap.containsKey(ename) && kpiMap.get(ename) > 0){
						long monthKpi = kpiMap.get(ename);
						value.append(vt.qfw(monthKpi)+";");
						//月累计
						long monthData = (long)Double.parseDouble(reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month")).toString());
						int monthDaysNum = DateUtil.getDaysByMonth(nowDate); //当月总天数
						long subDay  = monthDaysNum - DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")) -1; //剩余天数
						
						long subKpiData = 0 ;
						if(subDay != 0 ){
							subKpiData = (monthKpi - monthData)/subDay;
						}else{
							subKpiData = (monthKpi - monthData);
						}
						value.append(vt.qfw(subKpiData)+";");
					}else{
						value.append("--"+";");
						value.append("--"+";");
					}
					rsList.add(value.toString());
				}

				context.put("nowDate",nowDate);
				context.put("yesterDate",yesterDate);
				context.put("lastWeek",lastWeek);
				context.put("rsList",rsList);
				
				
				VelocityEngine velocity  = new VelocityEngine();
				Velocity.setProperty("input.encoding", "utf-8");
				Velocity.setProperty("output.encoding", "utf-8");
				String content = templateContext;
				StringWriter out = new StringWriter();
				velocity.evaluate(context, out, "", content);
				content = out.toString();
				out.close();
				return content;
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		
		

		/**赶集联盟收入日报
		 */
		@SuppressWarnings("static-access")
		public String gjDayReport(String searchDate){
			try {
				//velocity对象
				VelocityContext context = new VelocityContext();
				Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
				context.put("tools",tools);
				//读取模板内容
				String filepath =PathUtil.getWFNamespaceFolder()+"/emailtemp/GJDayReport.html";
				ResourcesUtil.setCharset(Charset.forName("utf-8"));
				FileInputStream inputStream = new FileInputStream(new File(filepath));
				String templateContext = ResourcesUtil.readString2(inputStream);
				inputStream.close();
				
				Date  sDate = DateUtil.strToDate(searchDate, "yyyy-MM-dd");
				String nowDate = DateUtil.getStringDate(sDate,"yyyy-MM-dd");//查询日期（今）
				String yesterDate = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 1),"yyyy-MM-dd");//查询日期（昨）
				String lastWeek = DateUtil.getStringDate(DateUtil.getDateBefore(sDate, 7),"yyyy-MM-dd");//查询日期（一周）
				
				//收入汇总  - 分渠道收入及分渠道摊销数据
				List<AllianceDataSummaryVoForMail> rsNow = onlineRevenueService.ORIncomeData(" statDate='"+nowDate+"' "); //今日数据
				List<AllianceDataSummaryVoForMail> rsYester= onlineRevenueService.ORIncomeData(" statDate='"+yesterDate+"' ");//昨日数据
				List<AllianceDataSummaryVoForMail> rsLastWeek= onlineRevenueService.ORIncomeData(" statDate='"+lastWeek+"' ");//上周数据
				String monthFirstDay = DateUtil.getFirstDay(sDate);	//当月第一天
				List<AllianceDataSummaryVoForMail> rsMonth = onlineRevenueService.ORIncomeSumData(" statDate>='"+monthFirstDay+"' and statDate <='"+nowDate+"' "); //月累计数据
				if(null == rsNow || null == rsYester || null == rsLastWeek || null == rsMonth){  //数据缺失直接88
					return "";
				}
				
				//本月KPI目标
				String month = DateUtil.getStringDate(sDate,"yyyy-MM");//月份
				ORKpiTarget  kpi  =onlineRevenueService.getORKpiTarget(month);
				Map<String,Long> kpiMap = new HashMap<String,Long>();
				Field[] kpiFds = ORKpiTarget.class.getDeclaredFields();
				for(Field fd : kpiFds){
					String name = fd.getName();
					if(!"month".equals(name)){
						long value = Long.parseLong(reflectUtil.getGetterMethod(ORKpiTarget.class, ORKpiTarget.class.getDeclaredField(name)).invoke(kpi).toString());
						kpiMap.put(name, value);
					}
				}
				
				Map<String,AllianceDataSummaryVoForMail> dataMap = new HashMap<String, AllianceDataSummaryVoForMail>();
				dataMap.put(nowDate, rsNow.get(0));
				dataMap.put(yesterDate, rsYester.get(0));
				dataMap.put(lastWeek, rsLastWeek.get(0));
				dataMap.put("month", rsMonth.get(0));
				
				List<String>  dics = spu.getECDicByAnnotation(AllianceDataSummaryVoForMail.class);
				List<String>  rsList = new ArrayList<String>(); 
				Class<AllianceDataSummaryVoForMail> clazz = AllianceDataSummaryVoForMail.class;
				
				boolean deal = false;
				
				for(String dic : dics){
					String ename = dic.split(",")[0];
					String cname = dic.split(",")[1];
					
					
					if("allianceIncomeGJ".equals(ename)){
						deal = true;
					}
					
					if(!deal){ 
						continue;
					}
					
					
					StringBuffer value = new StringBuffer();
					value.append(cname+";"); //指标名
					
					//该指标的数据类型
					Field field = AllianceDataSummaryVoForMail.class.getDeclaredField(ename);
					Class<?> filedCls = field.getType();
					int  colType = 0; //数据类型  0 : 整型  1：浮点  2：百分比
					if(filedCls == int.class || filedCls == Integer.class || filedCls == long.class || filedCls == Long.class) {
						colType = 0 ; 
					}else if(filedCls == double.class || filedCls == Double.class) {
						if("adverPvRate".equals(ename) || "CTR".equals(ename)){ //此两类为百分比 其他为浮点
							colType = 2 ; 
						}else{
							colType = 1 ; 
						}
					} 
					//今日数据
					Object nowData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(nowDate));
					if(null != nowData){
						value.append(vt.tranValueByType(nowData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//昨日数据
					Object yesterData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(yesterDate));
					if(null != yesterData){
						value.append(vt.tranValueByType(yesterData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//环比
					if(null != nowData && null != yesterData){
						value.append(vt.compRate(nowData, yesterData)+";");
					}else{
						value.append("--"+";");
					}
					//上周数据
					Object lastWeekData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get(lastWeek));
					if(null != lastWeekData){
						value.append(vt.tranValueByType(lastWeekData, colType)+";");
					}else{
						value.append("--"+";");
					}
					//同比
					if(null != nowData && null != lastWeekData){
						value.append(vt.compRate(nowData, lastWeekData)+";");
					}else{
						value.append("--"+";");
					}
					//4类数据无需计算月累计和月均
					if("adverPvRate".equals(ename) || "CTR".equals(ename)  || "CPC".equals(ename)  || "ECPM".equals(ename)){
						value.append("--"+";"+"--"+";");
					}else{
						//月累计
						Object monthData = reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month"));
						if(null != monthData){
							value.append(vt.qfw((long)Double.parseDouble(monthData.toString()))+";");
						}else{
							value.append("--"+";");
						}
						//月均
						if(null != monthData){
							long  monthSum = (long)Double.parseDouble(monthData.toString());
							long subDay  = DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")); //总天数
							long avgData = monthSum/(subDay+1);
							value.append(vt.qfw(avgData)+";");
						}else{
							value.append("--"+";");
						}
					}
					
					//KPI月目标 && KPI剩余日均
					if(kpiMap.containsKey(ename) && kpiMap.get(ename) > 0){
						long monthKpi = kpiMap.get(ename);
						value.append(vt.qfw(monthKpi)+";");
						//月累计
						long monthData = (long)Double.parseDouble(reflectUtil.getGetterMethod(clazz, clazz.getDeclaredField(ename)).invoke(dataMap.get("month")).toString());
						int monthDaysNum = DateUtil.getDaysByMonth(nowDate); //当月总天数
						long subDay  = monthDaysNum - DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")) -1; //剩余天数
						
						long subKpiData = 0 ;
						if(subDay != 0 ){
							subKpiData = (monthKpi - monthData)/subDay;
						}else{
							subKpiData = (monthKpi - monthData);
						}
						value.append(vt.qfw(subKpiData)+";");
					}else{
						value.append("--"+";");
						value.append("--"+";");
					}
					rsList.add(value.toString());
				}

				context.put("nowDate",nowDate);
				context.put("yesterDate",yesterDate);
				context.put("lastWeek",lastWeek);
				context.put("rsList",rsList);
				
				
				VelocityEngine velocity  = new VelocityEngine();
				Velocity.setProperty("input.encoding", "utf-8");
				Velocity.setProperty("output.encoding", "utf-8");
				String content = templateContext;
				StringWriter out = new StringWriter();
				velocity.evaluate(context, out, "", content);
				content = out.toString();
				out.close();
				return content;
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		
		/**邮件报告发送
		 */
		public int  ReportSend(int sendtype,String date) throws Exception{
			List<EmailReportUser>  users = emailReportUserService.getListByCondition("sendtype="+sendtype);//发送用户
			if(null != users && !users.isEmpty()){
				String title = "";
				String content = "";
				ArrayList<String>  attachedFileList =  null;
				switch (sendtype) {
				case 14:
					content = onlineRevenueIncomeDayReport(date);
					title = "在线收入汇总数据日报 "+ date;
					break;
				case 48:
					content = jxydtDayReport(date);
					title = "驾校一点通联盟收入数据日报 "+ date;
					break;
				case 49:
					content = gjDayReport(date);
					title = "赶集联盟收入数据日报 "+ date;
					break;
				}
				if("".equals(content)){
					log.info("Data Error!");
					title = "数据报告邮件发送异常!~ "+ DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
					String warnContent  = "The Email report has error~~~ ";
					String emailAd = "huangliang@58.com;zhaoxiang@58.com";
					MailUtil.javaMailSend(title, warnContent, emailAd,null);
					return 0;
				}else{
					for(EmailReportUser user : users){
						String address =user.getEmail();
						int result = MailUtil.javaMailSend(title, content, address,attachedFileList);
						if(result == 1){
							log.info("Send email success! the E-mail is "+address);
						}else{
							log.info("Send email falied! the E-mail is "+address);
							title = "每日数据报告邮件发送异常!! "+ DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
							MailUtil.javaMailSend(title, "The Email report has error~~~ ", "huangliang@58.com;zhaoxiang@58.com",null);
							return 0;
						}
					}
					return 1;
				}
			}
			return 0;
		}
		
}

